package com.klbnt.datashare.service;

import com.klbnt.datashare.entity.Categories;
import com.klbnt.datashare.entity.Links;
import com.klbnt.datashare.entity.Nodes;
import com.klbnt.datashare.entity.ResponseData;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

@Service
public class GraphService {

    private static final String LABEL_PATH = "./data/label.csv";
    // 从 0 到 9
    private static final String LINK_PATH = "./data/results/adj_list-";
    private static final String LINK_PATH_POSTFIX = ".csv";


    public ResponseData getData(int time) {

        ResponseData responseData = new ResponseData();
        ArrayList<Links> links = new ArrayList<>();
        ArrayList<Nodes> nodes = new ArrayList<>();
        HashMap<Integer, Boolean> map = new HashMap<>();

        BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader(LABEL_PATH));
            String line = reader.readLine();
            int lineNum = 1;
            while (line != null) {
                String[] s = line.split(",");

                Nodes node = new Nodes();
                node.setId(lineNum + "");
                lineNum++;
                node.setCategory(Integer.parseInt(s[time]) + "");
                node.setName(lineNum + "");
                node.setValue(100.0);

                map.put(Integer.parseInt(s[0]), Boolean.TRUE);
                nodes.add(node);

                // read next line
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        responseData.setNodes(nodes);

        for (Nodes node : nodes) {
            node.setSymbolSize(map.keySet().size());
        }


        // time是从0开始
        try {
            String path = LINK_PATH + time + LINK_PATH_POSTFIX;
            reader = new BufferedReader(new FileReader(path));
            String line = reader.readLine();
            while (line != null) {
                String[] s = line.split(",");

                Links link = new Links();
                link.setSource(s[0]);
                link.setTarget(s[1]);
                links.add(link);

                // read next line
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


        responseData.setLinks(links);

        ArrayList<Categories> categories = new ArrayList<>();
        for (int integer : map.keySet()) {
            categories.add(new Categories(integer + ""));
        }
        responseData.setCategories(categories);

        return responseData;
    }
}
